#pragma once

#include <filetransfferstruct.h>
#include <filetransffermgr.h>
#include <miscutil.h>
#include <fstream>
#include <msg_node.h>
#include <json/json.h>
#include <Logicnode.h>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <filesystem>

constexpr auto FILE_PATH = "../res/file_download";

class FileTransfferWork {
public:
	FileTransfferWork() = default;

	void start();

	void postTask(std::shared_ptr<LogicNode> logicNode);

	void stop();

	~FileTransfferWork();
private:
	void handler(std::shared_ptr<LogicNode> logicNode);

	bool sendFile(FileType type, const std::string& filepath, std::shared_ptr<Session> session);

	std::shared_ptr<SendNode> readFile(FileType type, const std::shared_ptr<FileTransfferStruct>& transferStruct);

	/// <summary>
	/// 根据传入的 type ，返回对应的 response type
	/// </summary>
	/// <param name="type"></param>
	/// <returns></returns>
	FileType getFileResponseType(FileType type);

	/// <summary>
	/// 根据传入的 type ，返回对应的 finish type
	/// </summary>
	/// <param name="type"></param>
	/// <returns></returns>
	FileType getFileFinishType(FileType type);


	/// <summary>
	/// 根据消息类型、该消息类型的具体错误类型、错误信息创建错误数据包
	/// </summary>
	/// <param name="errorType"></param>
	/// <param name="msg"></param>
	/// <returns></returns>
	std::shared_ptr<SendNode> getErrorNode(MsgType msgType, FileErrorType errorType, std::string msg);

private:
	std::queue<std::shared_ptr<LogicNode>> logicQueue_;
	std::shared_ptr<std::thread> workThread_;
	std::mutex logicLock_;
	std::condition_variable logicCond_;
	bool isStop_;

	std::unordered_map<FileType, std::function<void()>> fileHandler_; // todo：后面优化的时候用来保存不同类型的FileType的处理函数
};